package com.atguigu.tingshu.payment.api;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.common.annotation.login.LoginRequired;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付接口
 *
 * @author sun
 */
@RestController
@RequestMapping("api/payment/wxPay")
@Slf4j
public class WxPayApiController {

    @Resource
    private WxPayService wxPayService;
    @Resource
    private PaymentInfoService paymentInfoService;

    /**
     * 微信支付
     *
     * @param type    支付类型：1301-订单 1302-充值
     * @param orderNo 订单号
     * @return map 集合
     */

    @PostMapping("createJsapi/{type}/{orderNo}")
    @LoginRequired
    public Result<Map<String, Object>> creatJsapi(
            @PathVariable("type") String type,
            @PathVariable("orderNo") String orderNo
    ) {
        return Result.ok(wxPayService.creatJsapi(type, orderNo));
    }

    /**
     * 获取支付二维码
     * @param type 支付类型：1301-订单 1302-充值
     * @param orderNo 订单号
     * @return 二维码地址
     */
    @GetMapping("getNativeUrl/{type}/{orderNo}")
    @LoginRequired
    public Result<String> getNativeUrl(@PathVariable("type") String type,
                                       @PathVariable("orderNo") String orderNo){
        return Result.ok(wxPayService.getNativeUrl(type, orderNo));
    }


    /**
     * 查询支付状态
     *
     * @param orderNo 订单号
     * @return 是否支付成功
     */
    @GetMapping("queryPayStatus/{orderNo}")
    @LoginRequired
    public Result<Boolean> queryPayStatus(@PathVariable("orderNo") String orderNo) {

        Transaction transaction = wxPayService.queryPayStatus(orderNo);
        log.info("支付状态查询：{}", JSONObject.toJSONString(transaction));
        if (null != transaction && transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
            //更改订单状态
            paymentInfoService.updatePaymentStatus(transaction);
            return Result.ok(true);
        }

        return Result.ok(false);
    }

    /**
     * 微信支付回调
     * @param request 请求
     * @return 返回的参数
     */
    @PostMapping("notify")
    public Result<Map<String, Object>> notify(HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();
        Boolean result = wxPayService.wxPayNotify(request);
        if(result){
            map.put("code", "SUCCESS");
            map.put("msg", "OK");
        }else{
            map.put("code", "FAIL");
            map.put("msg", "FAIL");
        }
        return Result.ok(map);
    }


}
